package component;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTable;
import javax.swing.KeyStroke;

import org.jdesktop.swingx.JXSearchField;

@SuppressWarnings("serial")
public class ExtendedJXSearchField extends JXSearchField {
	private JTable table;
	private Action searchAction;

	public ExtendedJXSearchField(JTable table) {
		this.table = table;
		initListeners();
	}

	private void initListeners() {
		addKeyListener(new KeyAdapter() {

			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_DOWN) {
					table.grabFocus();
					if(table.getSelectedRowCount() == 0){
						table.getSelectionModel().addSelectionInterval(0, 0);
					}
				}
			}

		});
	}

	public Action getSearchAction() {
		if (searchAction == null) {
			searchAction = new SearchAction();
		}
		return searchAction;
	}

	private class SearchAction extends AbstractAction {

		public SearchAction() {
			super("Suche", Icons.SEARCH);
			putValue(AbstractAction.ACCELERATOR_KEY,
					KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK));
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			ExtendedJXSearchField.this.grabFocus();
			ExtendedJXSearchField.this.selectAll();
		}

	}
}
